package com.readfeed.app;

import java.util.List;

import com.readfeed.app.data.FeedsAdapter;
import com.readfeed.app.model.Category;
import android.app.Activity;
import android.app.Fragment;
import android.os.AsyncTask;
import android.os.Bundle;

public class GetCategoriesTaskFragment extends Fragment {
	
	  private TaskCallbacks mCallbacks;
	  private GetCategoriesTask mTask;
	  private boolean mRunning;
	  private List<Category> categoriesList;
	 
	  @Override
	  public void onAttach(Activity activity) {		  		 
		  super.onAttach(activity);
		  if (!(activity instanceof TaskCallbacks)) {
			  throw new IllegalStateException("Activity must implement the TaskCallbacks interface.");
	      	}
	    
		  mCallbacks = (TaskCallbacks) activity;
	  }
	 
	  @Override
	  public void onCreate(Bundle savedInstanceState) {
		  super.onCreate(savedInstanceState);	 
		  setRetainInstance(true);	 
	  }
	  
	  public List<Category> getResult(){
		  return this.categoriesList;
	  }
	  
	  public void executeTask(){
		  if (!mRunning) {
			  mTask = new GetCategoriesTask();
			  mTask.execute();
			  mRunning = true;			 
		  }		  
	  }
	  
	  public void cancelTask(){
		  if (mRunning) {
			  mTask.cancel(false);
			  mTask = null;
			  mRunning = false;
		  }
	  }
	 
	  @Override
	  public void onDetach() {
		  super.onDetach();
		  mCallbacks = null;
	  }
	 
	  private class GetCategoriesTask extends AsyncTask<Void, Integer, Void> {
	 		  
	  	@Override
	  	protected void onPreExecute() {	    	
	  		if (mCallbacks != null) {
	  			mCallbacks.onPreExecute();
	  		}
	  	}
	 	    
	    @Override
	    protected Void doInBackground(Void... ignore) {
//	    	FeedsAdapter feedAdapter = new FeedsAdapter(getActivity());
//	    	feedAdapter.open();
//	    	categoriesList = feedAdapter.getAllCategories();	    	
//	    	feedAdapter.close();
	    	
	    	return null;
	    }	 	   
	 
	    @Override
	    protected void onCancelled() {
	    	if (mCallbacks != null) {
	    		mCallbacks.onCancelled();
	    	}
	      
	    	mRunning = false;
	    }
	 
	    @Override
	    protected void onPostExecute(Void ignore) {	    	
	    	if (mCallbacks != null) {
	    		mCallbacks.onPostExecute(1);
	    	}
	      
	    	mRunning = false;
	    }
	  }
}
